package com.lw.leetcode.stack.b;

import java.util.Stack;

/**
 * 1190. 反转每对括号间的子串
 *
 * @Author liw
 * @Date 2021/5/17 13:59
 * @Version 1.0
 */
public class ReverseParentheses {

    public static void main(String[] args) {
        ReverseParentheses test = new ReverseParentheses();

        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String s = test.reverseParentheses(i + "  :  " + "(ed(et(oc))el)");
            System.out.println(s);
        }

    }
    // "(()))(()))()())))"

    public String reverseParentheses(String s) {
        Stack<Character> stack = new Stack<>();
        int length = s.length();
        char[] arr = new char[length];
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == ')') {
                int index = 0;
                while ((c = stack.pop()) != '(') {
                    arr[index++] = c;
                }
                for (int j = 0; j < index; j++) {
                    stack.add(arr[j]);
                }
            } else {
                stack.add(c);
            }
        }
        int index = length - 1;
        while (!stack.isEmpty()) {
            arr[index--] = stack.pop();
        }
        return new String(arr, index + 1, length - index - 1);
    }

}
